package com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.repository.entity.HddcB1GeologysvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.entity.HddcGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.repository.HddcMainafsvyregionNativeRepository;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.repository.HddcMainafsvyregionRepository;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.repository.entity.HddcMainafsvyregionEntity;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.service.HddcMainafsvyregionService;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.viewobjects.HddcMainafsvyregionQueryParams;
import com.css.zfzx.sjcj.modules.hddcMainAFSvyRegion.viewobjects.HddcMainafsvyregionVO;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.entity.HddcTargetregionEntity;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.service.HddcTargetregionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zyb
 * @date 2020-12-14
 */
@Service
public class HddcMainafsvyregionServiceImpl implements HddcMainafsvyregionService {

	@Autowired
    private HddcMainafsvyregionRepository hddcMainafsvyregionRepository;
    @Autowired
    private HddcMainafsvyregionNativeRepository hddcMainafsvyregionNativeRepository;
    @Autowired
    private HddcTargetregionService hddcTargetregionService;

    @Override
    public JSONObject queryHddcMainafsvyregions(HddcMainafsvyregionQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcMainafsvyregionEntity> hddcMainafsvyregionPage = this.hddcMainafsvyregionNativeRepository.queryHddcMainafsvyregions(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcMainafsvyregionPage);
        return jsonObject;
    }


    @Override
    public HddcMainafsvyregionEntity getHddcMainafsvyregion(String id) {
        HddcMainafsvyregionEntity hddcMainafsvyregion = this.hddcMainafsvyregionRepository.findById(id).orElse(null);
         return hddcMainafsvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcMainafsvyregionEntity saveHddcMainafsvyregion(HddcMainafsvyregionEntity hddcMainafsvyregion) {
        String uuid = UUIDGenerator.getUUID();
        hddcMainafsvyregion.setUuid(uuid);
        hddcMainafsvyregion.setCreateUser(PlatformSessionUtils.getUserId());
        hddcMainafsvyregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcMainafsvyregion.setIsValid("1");
        this.hddcMainafsvyregionRepository.save(hddcMainafsvyregion);
        return hddcMainafsvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcMainafsvyregionEntity updateHddcMainafsvyregion(HddcMainafsvyregionEntity hddcMainafsvyregion) {
        UpdateUtil.copyNullProperties(hddcMainafsvyregionRepository.findByUuidAndIsValid(hddcMainafsvyregion.getUuid(), "1"), hddcMainafsvyregion);
        hddcMainafsvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcMainafsvyregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcMainafsvyregionRepository.save(hddcMainafsvyregion);
        return hddcMainafsvyregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcMainafsvyregions(List<String> ids) {
        List<HddcMainafsvyregionEntity> hddcMainafsvyregionList = this.hddcMainafsvyregionRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcMainafsvyregionList) && hddcMainafsvyregionList.size() > 0) {
            for(HddcMainafsvyregionEntity hddcMainafsvyregion : hddcMainafsvyregionList) {
                hddcMainafsvyregion.setIsValid("0");
                hddcMainafsvyregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcMainafsvyregion.setUpdateTime(new Date());
                this.hddcMainafsvyregionRepository.save(hddcMainafsvyregion);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcMainafsvyregionQueryParams queryParams, HttpServletResponse response) {
        List<HddcMainafsvyregionEntity> yhDisasterEntities = hddcMainafsvyregionNativeRepository.exportYhDisasters(queryParams);
        List<HddcMainafsvyregionVO> list=new ArrayList<>();
        for (HddcMainafsvyregionEntity entity:yhDisasterEntities) {
            HddcMainafsvyregionVO yhDisasterVO=new HddcMainafsvyregionVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"主要活动断层制图区-面","主要活动断层制图区-面",HddcMainafsvyregionVO.class,"主要活动断层制图区-面.xls",response);
    }


    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcMainafsvyregionVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcMainafsvyregionVO.class, params);
            List<HddcMainafsvyregionVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcMainafsvyregionVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcMainafsvyregionVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcMainafsvyregionEntity> listAll = hddcMainafsvyregionRepository.findByAll();
        for (HddcMainafsvyregionEntity b2All: listAll) {
            String str="";
            if (StringUtils.isEmpty(b2All.getTargetregionid())) {
                continue;
            }
            HddcTargetregionEntity hddcTargetregionEntity =  hddcTargetregionService.findById(b2All.getTargetregionid());
            if (hddcTargetregionEntity==null){
                hddcMainafsvyregionRepository.updateStatus("2","质检失败",b2All.getUuid());
                continue;
            }
            System.out.println(b2All.getMappingarea());
            if(b2All.getMappingarea() ==null || !(b2All.getMappingarea().equals(hddcTargetregionEntity.getMappingarea()))){
                str+= "地质填图面积 [km²]失败";
            }
            if(b2All.getRsprocess()==null || !(b2All.getRsprocess().equals(hddcTargetregionEntity.getRsprocess()))){
                str+= "遥感影像处理数目失败";
            }
            if(b2All.getFieldsvyptcount()==null || !(b2All.getFieldsvyptcount().equals(hddcTargetregionEntity.getFieldsvyptcount()))){
                str+= "野外观测点数失败";
            }
            if(b2All.getTrenchcount()==null || StringUtils.isEmpty(b2All.getTrenchcount()) && !(b2All.getTrenchcount().equals(hddcTargetregionEntity.getTrenchcount()))){
                str+= "探槽数失败";
            }
            if(b2All.getTrenchvolume()==null || !(b2All.getTrenchvolume().equals(hddcTargetregionEntity.getTrenchvolume()))){
                str+= "探测总土方量 [m³]失败";
            }
            if(b2All.getDrillcount() ==null || !(b2All.getDrillcount().equals(hddcTargetregionEntity.getDrillcount()))){
                str+= "钻孔数失败";
            }
            if(b2All.getDrilllength()==null || !(b2All.getDrilllength().equals(hddcTargetregionEntity.getDrilllength()))){
                str+= "钻孔进尺 [米]失败";
            }
            if(b2All.getGphwellcount()==null || !(b2All.getGphwellcount().equals(hddcTargetregionEntity.getGphwellcount()))){
                str+= "地球物理测井数失败";
            }
            if(b2All.getCollectedsamplecount()==null || !(b2All.getCollectedsamplecount().equals(hddcTargetregionEntity.getCollectedsamplecount()))){
                str+= "采集样品总数失败";
            }
            if(b2All.getSamplecount() ==null || !(b2All.getSamplecount().equals(hddcTargetregionEntity.getSamplecount()))){
                str+= "送样总数失败";
            }
            if(b2All.getDatingsamplecount()==null || !(b2All.getDatingsamplecount().equals(hddcTargetregionEntity.getDatingsamplecount()))){
                str+= "获得测试结果样品数失败";
            }
            if(b2All.getGeomorphysvyprojectcount()==null || !(b2All.getGeomorphysvyprojectcount()==hddcTargetregionEntity.getGeomorphysvyprojectcount())){
                str+= "微地貌测量工程总数失败";
            }
            if(b2All.getSeismicprojectcount()==null || !(b2All.getSeismicprojectcount()==hddcTargetregionEntity.getSeismicprojectcount())){
                str+= "地震监测工程数失败";
            }
            if(b2All.getCrustaldfmprojectcount()==null || !(b2All.getCrustaldfmprojectcount()==hddcTargetregionEntity.getCrustaldfmprojectcount())){
                str+= "地形变监测工程数失败";
            }
            if(b2All.getGeophysicalsvyprojectcount()==null || !(b2All.getGeophysicalsvyprojectcount()==hddcTargetregionEntity.getGeophysicalsvyprojectcount())){
                str+= "地球物理探测工程数失败";
            }
            if(b2All.getGeochemicalprojectcount()==null || !(b2All.getGeochemicalprojectcount()==hddcTargetregionEntity.getGeochemicalprojectcount())){
                str+= "地球化学探测工程数失败";
            }
            if(b2All.getIsvolcanic()==null || !(b2All.getIsvolcanic()==hddcTargetregionEntity.getIsvolcanic())){
                str+= "是否火山地质调查填图失败";
            }
            if(b2All.getSra()==null || !(b2All.getSra()==hddcTargetregionEntity.getSra())){
                str+= "是否开展地震危险性评价失败";
            }
            if(StringUtils.isEmpty(b2All.getSda()) && !(b2All.getSda()==hddcTargetregionEntity.getSda())){
                str+= "是否开展地震危害性评价失败";
            }
            if(str.isEmpty()){
                str +="质检成功";
                hddcMainafsvyregionRepository.updateStatus("1",str,b2All.getUuid());
            }else{
                hddcMainafsvyregionRepository.updateStatus("2",str,b2All.getUuid());
            }
        }
        return 1;
    }

    @Override
    public HddcMainafsvyregionEntity findbyId(String id) {
        HddcMainafsvyregionEntity hddcMainafsvyregionEntity= hddcMainafsvyregionRepository.finbyId(id);
        return hddcMainafsvyregionEntity;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcMainafsvyregionVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcMainafsvyregionEntity yhDisasterEntity = new HddcMainafsvyregionEntity();
            HddcMainafsvyregionVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcMainafsvyregion(yhDisasterEntity);
        }
    }

}
